const app = getApp()
import { list, detail, save, remove } from '../../../api/mine/address'
import Dialog from '../../../miniprogram_npm/@vant/weapp/dialog/dialog'
const chooseLocation = requirePlugin('chooseLocation')

Page({
  data: {
    back: true,
    title: '地址管理',
    loading: true,
    submitLoading: false,
    loadmore: false,
    show: false,
    list: null,
    order: null, // 是否来自订单确认页
    form: {
      page: 1,
      limit: 10
    },
    submit: {
      id: null,
      contact: '',
      phone: '',
      province: '',
      city: '',
      district: '',
      postcode: '',
      detail: '',
      num: '',
      lon: '',
      lat: '',
      is_default: false
    },
    abnor: {
      title: '好像还没有添加地址哦~',
      button: ''
    }
  },
  onLoad (options) {
    options.order && (this.data.order = true)
    this.setData({ loading: true })
    this.getList()
  },
  onShow () {
     // 如果点击确认选点按钮，则返回选点结果对象，否则返回null
    const location = chooseLocation.getLocation()
    if (location != null) {
      let submit = this.data.submit
      submit = {
        id: submit.id,
        contact: submit.contact,
        phone: submit.phone,
        lon: location.longitude.toString(),
        lat: location.latitude.toString(),
        province: location.province,
        city: location.city,
        district: location.district,
        detail: location.name,
        num: submit.num,
        is_default: submit.is_default
      }
      this.setData({ submit: submit })
    }
  },
  onPullDownRefresh () { /* 监听用户下拉动作*/ },
  onReachBottom () {
    if (this.data.form.page == this.data.form.last_page) {
      this.setData({ loadmore: true })
    } else {
      this.data.form.page += 1
      this.getList()
    }
  },

  // ===================methon================

  getList () {
    list(this.data.form).then(res => {
      const { data } = res
      this.data.list || (this.data.list = [])
      const list = this.data.list.concat(data.data)
      this.data.form.last_page = res.data.last_page
      this.setData({
        list: list,
        loadmore: data.last_page <= 1
      })
    })
      .finally(() => {
        this.setData({ loading: false });
      })
  },

  submit () {
    const submit = this.data.submit
    if (submit.contact.trim() == '') {
      app.toast('请输入您的姓名')
      return false
    }
    if (!/^1[3|4|5|7|8][0-9]\d{8}$/.test(submit.phone.trim())) {
      app.toast('请输入正确的手机号码')
      return false
    }
    if (submit.detail.trim() == '') {
      app.toast('请选择详细地址')
      return false
    }
    this.setData({ submitLoading: true })
    submit.is_default = submit.is_default ? 20 : 10
    save(submit).then(res => {
      app.toast(res.msg)
      this.onClose()
      this.init()
      this.getList()
    })
      .finally(() => {
        this.setData({ submitLoading: false })
      })
  },

  remove (event) {
    const id = event.currentTarget.dataset.id
    const list = []
    const that = this
    this.data.list.forEach(item => {
      if (item.id != id) {
        list.push(item)
      }
    })
    Dialog.confirm({
      message: '确定删除这个地址吗？'
    }).then(() => {
      remove(id).then(res => {
        app.toast('删除成功')
        that.setData({
          list: list
        })
        that.onClose()
      })
    }).catch(() => { })
  },

  edit (event) {
    const id = event.currentTarget.dataset.id
    detail(id).then(res => {
      const detail = res.data
      detail.is_default = detail.is_default == 20
      this.setData({
        submit: detail,
        show: true
      })
    })
  },

  auth () {
    return new Promise((resolve, reject) => {
      wx.getSetting({
        success (res) {
          if (res.authSetting['scope.userLocation'] == true ||
          res.authSetting['scope.userLocation'] == undefined) {
            resolve()
          } else {
            wx.openSetting({
              success (res) {
                if (res.authSetting['scope.userLocation'] == true) {
                  resolve()
                } else {
                  reject()
                }
              }
            })
          }
        }
      })
    })
  },

  location () {
    this.auth().then(res => {
      const setting = app.global.setting.location
      wx.getLocation({
        success (res) {
          const key = setting.key // 使用在腾讯位置服务申请的key
          const referer = setting.name // 调用插件的app的名称
          const location = JSON.stringify({
            latitude: res.latitude,
            longitude: res.longitude
          })
          wx.navigateTo({
            url: `plugin://chooseLocation/index?key=${key}&referer=${referer}&location=${location}`
          })
        }
      })
    })
      .catch(e => {
        Dialog.alert({
          message: '使用此功能需要您的授权'
        }).then(() => {}).catch(() => { })
      })
  },

  onAdd () {
    this.onClose()
    this.setData({ show: true })
  },

  onClose () {
    this.setData({
      show: false,
      submit: {
        id: null,
        contact: '',
        phone: '',
        province: '',
        city: '',
        district: '',
        detail: '',
        num: '',
        is_default: false
      }
    })
  },

  setNum (event) {
    const submit = this.data.submit
    submit.num = event.detail
    this.setData({ submit: submit })
  },

  setContact (event) {
    const submit = this.data.submit
    submit.contact = event.detail
    this.setData({ submit: submit })
  },

  setPhone (event) {
    const submit = this.data.submit
    submit.phone = event.detail
    this.setData({ submit: submit })
  },

  setDefault (event) {
    const submit = this.data.submit
    submit.is_default = event.detail
    this.setData({ submit: submit })
  },

  init () {
    this.setData({
      list: null,
      loadmore: false,
      form: {
        page: 1,
        limit: 10
      }
    })
  },

  selectAddress (event) {
    if (this.data.order) {
      wx.setStorageSync('address', event.currentTarget.dataset.id)
      wx.navigateBack({
        delta: 1
      })
    }
  }
})